package com.java.business.jxc.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.java.business.jxc.bean.B_INPUT;
import com.java.business.jxc.bean.B_MATERIAL;
import com.java.business.jxc.bean.B_OUTPUT;
import com.java.business.jxc.dao.InputMapper;
import com.java.business.jxc.dao.MaterialMapper;
import com.java.business.jxc.dao.OutputMapper;
import com.java.core.bean.LowerCaseKeyMap;
import com.java.core.utils.IdUtils;

@Transactional
@Service
public class InputService {

	@Autowired
	private InputMapper mapper;

	@Autowired
	private OutputMapper outputMapper;

	@Autowired
	private MaterialMapper materialMapper;

	public void add(B_INPUT input) {
		input.setInput_id(IdUtils.uuid());
		mapper.add(input);
	}

	public void update(B_INPUT input) {
		Double amount = mapper.getInputById(input.getInput_id()).getAmount();
		B_OUTPUT output = new B_OUTPUT();
		output.setMaterial_id(input.getMaterial_id());
		Double outputAmount = outputMapper.getOutputAmount(output);
		B_MATERIAL material = materialMapper.getMaterialById(input.getMaterial_id());
		Double totalAmount = material.getTotal_amount();
		if (totalAmount - amount + input.getAmount() < outputAmount) {
			throw new RuntimeException("当前进货数量 " + input.getAmount() + " 加上已进货数量 " + (totalAmount - amount)
					+ " 不能小于出库总量 " + outputAmount + "!");
		}
		mapper.update(input);
	}

	public void setDisabled(B_INPUT input) {
		mapper.setDisabled(input);
	}

	public void delete(String input_id) {
		// 获取入库信息
		B_INPUT input = mapper.getInputById(input_id);
		// 获取出库总量
		B_OUTPUT output = new B_OUTPUT();
		output.setMaterial_id(input.getMaterial_id());
		Double outputAmount = outputMapper.getOutputAmount(output);
		// 获取总量
		B_MATERIAL material = materialMapper.getMaterialById(input.getMaterial_id());
		Double totalAmount = material.getTotal_amount();
		if (totalAmount - input.getAmount() < outputAmount) {
			throw new RuntimeException("无法删除该进货信息，删除当前进货数量 " + input.getAmount() + " 会使进货总量 " + totalAmount + " 小于出库总量 "
					+ outputAmount + "!");
		}
		mapper.delete(input_id);
	}

	public B_INPUT getInputById(String input_id) {
		return mapper.getInputById(input_id);
	}

	public List<LowerCaseKeyMap> getInputList(B_INPUT input) {
		return mapper.getInputList(input);
	}
}
